package io

import (
	"fmt"
	"os"
	"zeno-kv/record"
)


type FileIO struct {
	activeFile *os.File
	oldFiles   []*os.File
}

func NewFileIO(path string) *FileIO {
	m := &FileIO{
		oldFiles: make([]*os.File, 0),
	}
	files, err := os.ReadDir(path)
	if err != nil {
		fmt.Printf("open path error: %v\n", err)
		return nil
	}

	if len(files) == 0 {
		fmt.Printf("data dir is empty, create a active file\n")
		f, err := os.OpenFile(fmt.Sprintf("%s/%s", path, "active"), os.O_CREATE, 0644)
		if err != nil {
			fmt.Printf("create active file fail, err: %v\n", err)
		}
		m.activeFile = f
		return m
	}

	for _, file := range files {
		if file.Name() == "active" {
			m.activeFile, err = os.OpenFile(file.Name(), os.O_APPEND, 0644)
			if err != nil {
				fmt.Printf("Open Active file fail, err: %v\n", err)
			}
		} else {
			f, err := os.OpenFile(file.Name(), os.O_RDONLY, 0644)
			if err != nil {
				fmt.Printf("Open old file fail, err: %v\n", err)
			}
			m.oldFiles = append(m.oldFiles, f)
		}
	}

	return m
}

func (f *FileIO) Write(record []byte) error {
	return nil
}

// Read 从文件中读出记录，需要给出fileId用于定位文件
func (f *FileIO) Read(fileId uint32, pos uint32, valueSize uint64) *record.Record {
	return nil
}